// map.js
import qqMap from '../../../utils/qqmap'
Page({
  data: {
    latitude: 31.849235,
    longitude: 117.133214,
    markers: [
      {
        id: 1,
        latitude: 31.849235,
        longitude: 117.133214,
        width: 25,
        height: 30,
      },
      {
        id: 2,
        latitude: 31.831007,
        longitude: 117.168154,
        iconPath: '/static/images/marker.png',
        width: 40,
        height: 40,
      },
    ],
    polyline:[],
    repairDetail: {}
  },
  onLoad({id}) {
    // 获取报修详情的数据
    this.getRepairDetail(id)
     // 生成路线
     this.getPolyline()
  },
  // 报修详情接口
  async getRepairDetail(id) {
    // 调用接口
    const repairDetail = await wx.http.get('/repair/' + id)
    // 渲染数据
    this.setData({ repairDetail })
  },
  // 调用位置服务（路线规划）
  getPolyline() {
    console.log('路径规划')
    qqMap.direction({
      mode: 'bicycling',
      from: `${this.data.markers[0].latitude},${this.data.markers[0].longitude}`,
      to: `${this.data.markers[1].latitude},${this.data.markers[1].longitude}`,
      success: ({ result }) => {
        const coors = result.routes[0].polyline
        const points = []
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        for (let i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / 1000000
        }
        // 获取经纬度
        for (let i = 0; i < coors.length; i += 2) {
          points.push({ latitude: coors[i], longitude: coors[i + 1] })
        }
        // 渲染数据
        this.setData({
          latitude: points[30].latitude,
          longitude: points[30].longitude,
          polyline: [{ points, color: '#5591af', width: 4 }],
        })
      },
    })
  },
})